package com.initialize.appapi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.initialize.pub.mybatis.plus.entity.Article;
import com.initialize.pub.mybatis.plus.entity.Label;
import com.initialize.pub.mybatis.plus.service.impl.ArticleServiceImpl;
import com.initialize.pub.mybatis.plus.service.impl.LabelServiceImpl;
import com.initialize.pub.token.UserLoginToken;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: jane
 * Date: 2020/3/13
 * Time: 9:49 下午
 * Description:
 */

@Api(tags = "标签API")
@RestController
@CrossOrigin
@RequestMapping(value = "/label")
public class TagController {
    @Autowired
    LabelServiceImpl labelService;


    @ApiOperation("获取标签的数量")
    @PostMapping("/count")
    @UserLoginToken
    public R<Integer> getTheNumberOfTags() {
        return R.ok(labelService.count());
    }


    @ApiOperation("获取所有的标签")
    @PostMapping("/list")
    @UserLoginToken
    public R<List<Label>> getAllTags() {
        return R.ok(labelService.list());
    }


    @ApiOperation("更新标签")
    @PostMapping("/update")
    @UserLoginToken
    public R<Boolean> update(@RequestBody Label label) {
        return R.ok(labelService.updateById(label));
    }

    @Autowired
    ArticleServiceImpl articleService;

    @ApiOperation("删除标签")
    @PostMapping("/delete")
    @UserLoginToken
    public R<Boolean> delete(@RequestBody List<Integer> label) {
        label.forEach(o -> {
            List<Article> articleList = articleService.list(new QueryWrapper<Article>().like("label", o));
            articleList.forEach(label1 -> {
                String replace = label1.getLabel().replace(o.toString(), "").replace("||", "|");
                if (replace.length() == 1) {
                    replace = "";
                }
                label1.setLabel(replace);
                articleService.updateById(label1);
            });
        });
        return R.ok(labelService.removeByIds(label));
    }


    @ApiOperation("添加的标签")
    @PutMapping("/{name}")
    @UserLoginToken
    public R<List<Label>> addTag(@PathVariable String name) {
        Label label = Label.builder().name(name.trim()).build();
        labelService.save(label);
        return R.ok(labelService.list());
    }

    @ApiOperation("根据id获取标签")
    @GetMapping("/id/{aid}")
    @UserLoginToken
    public R<Label> addTag(@PathVariable int aid) {
        return R.ok(labelService.getById(aid));
    }

}